<template>
  <view class="publish-container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="nav-bar">
        <view class="back-btn" @click="goBack">
          <text class="back-icon">‹</text>
        </view>
        <text class="page-title">发布圈子</text>
        <view class="menu-btn">
          <text class="menu-icon">⋯</text>
        </view>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="content-section">
      <view class="section-header">
        <view class="section-icon">📝</view>
        <text class="section-title">内容</text>
      </view>

      <view class="content-input">
        <textarea
          v-model="content"
          placeholder="请输入此刻的想法"
          class="textarea"
          :maxlength="500"
          auto-height
        ></textarea>
      </view>

      <!-- 媒体预览区域 -->
      <view class="media-preview">
        <!-- 已上传的媒体文件 -->
        <view
          v-for="(media, index) in mediaFiles"
          :key="index"
          class="media-item"
        >
          <!-- 图片预览 -->
          <image
            v-if="media.type === 'image'"
            :src="media.url"
            class="preview-image"
            mode="aspectFill"
            @click="previewImage(index)"
          ></image>
          <!-- 视频预览 -->
          <view v-else-if="media.type === 'video'" class="video-preview">
            <video
              :src="media.url"
              class="preview-video"
              :poster="media.poster"
              controls
            ></video>
            <view class="video-overlay">
              <text class="play-icon">▶</text>
            </view>
          </view>
          <view class="delete-btn" @click="deleteMedia(index)">
            <text class="delete-icon">×</text>
          </view>
        </view>

        <!-- 添加媒体按钮 - 始终在最后 -->
        <view
          v-if="mediaFiles.length < 9"
          class="add-media-btn"
          @click="showMediaSelector"
        >
          <text class="add-icon">+</text>
        </view>
      </view>
    </view>

    <!-- 圈子类型 -->
    <view class="category-section">
      <view class="section-header">
        <view class="section-icon">🏷️</view>
        <text class="section-title">圈子类型</text>
      </view>

      <view class="category-tags">
        <view
          v-for="(category, index) in categories"
          :key="index"
          class="category-tag"
          :class="{ active: selectedCategory === category.id }"
          @click="selectCategory(category.id)"
        >
          {{ category.name }}
        </view>
      </view>
    </view>

    <!-- 选择话题 -->
    <view class="topic-section" @click="goToTopicSelect">
      <view class="section-header">
        <view class="section-icon">#</view>
        <text class="section-title">选择话题</text>
        <text class="arrow-icon">›</text>
      </view>
    </view>

    <!-- 发布设置 -->
    <view class="settings-section">
      <view class="setting-item">
        <text class="setting-label">是否使用匿名发布</text>
        <switch
          :checked="isAnonymous"
          @change="onAnonymousChange"
          color="#FF6E26"
          class="setting-switch"
        />
      </view>

      <view class="setting-item">
        <text class="setting-label">置顶圈子</text>
        <switch
          :checked="isTop"
          @change="onTopChange"
          color="#FF6E26"
          class="setting-switch"
        />
      </view>
    </view>

    <!-- 发布按钮 -->
    <view class="publish-btn-container">
      <button
        class="publish-btn"
        :class="{ disabled: !canPublish }"
        @click="publishPost"
        :disabled="!canPublish"
      >
        发布
      </button>
    </view>

    <!-- 媒体选择弹窗 -->
    <view v-if="showMediaModal" class="media-modal" @click="hideMediaSelector">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">提示</text>
        </view>
        <view class="modal-body">
          <text class="modal-text">请选择上传格式</text>
        </view>
        <view class="modal-actions">
          <button class="action-btn image-btn" @click="chooseImage">
            图片
          </button>
          <button class="action-btn video-btn" @click="chooseVideo">
            视频
          </button>
        </view>
      </view>
    </view>

    <!-- 图片预览弹窗 -->
    <view
      v-if="showImagePreview"
      class="image-preview-modal"
      @click="closeImagePreview"
    >
      <view class="preview-container">
        <!-- 预览图片 -->
        <swiper
          class="preview-swiper"
          :current="currentPreviewIndex"
          @change="onSwiperChange"
          :indicator-dots="imageUrls.length > 1"
          indicator-color="rgba(255,255,255,0.5)"
          indicator-active-color="#fff"
        >
          <swiper-item v-for="(url, index) in imageUrls" :key="index">
            <view class="swiper-item-container" @click.stop>
              <image
                :src="url"
                class="preview-full-image"
                mode="aspectFit"
                @click.stop
              />
            </view>
          </swiper-item>
        </swiper>

        <!-- 关闭按钮 -->
        <view class="close-preview-btn" @click="closeImagePreview">
          <text class="close-icon">×</text>
        </view>

        <!-- 图片索引 -->
        <view v-if="imageUrls.length > 1" class="image-counter">
          <text class="counter-text"
            >{{ currentPreviewIndex + 1 }} / {{ imageUrls.length }}</text
          >
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";

// 声明uni全局对象
declare const uni: any;

// 定义类型接口
interface MediaFile {
  type: "image" | "video";
  url: string;
  size: number;
  poster?: string;
  duration?: number;
  filename?: string; // 添加文件名字段
}

interface Category {
  id: string;
  name: string;
}

interface PostData {
  content: string;
  mediaFiles: MediaFile[];
  category: string;
  isAnonymous: boolean;
  isTop: boolean;
  timestamp: number;
}

// 响应式数据
const content = ref<string>("");
const mediaFiles = ref<MediaFile[]>([]);
const selectedCategory = ref<string>("help");
const isAnonymous = ref<boolean>(false);
const isTop = ref<boolean>(false);
const showMediaModal = ref<boolean>(false);
const showImagePreview = ref<boolean>(false);
const currentPreviewIndex = ref<number>(0);

// 分类数据
const categories = ref<Category[]>([
  { id: "help", name: "互相补差价" },
  { id: "insurance", name: "保理西院" },
  { id: "confession", name: "表白捞人" },
  { id: "complain", name: "树洞吐槽" },
  { id: "game", name: "游戏开黑" },
  { id: "eat", name: "八卦吃瓜" },
  { id: "chat", name: "匿名闲聊" },
  { id: "vibrant", name: "振涛" },
]);

// 计算属性
const canPublish = computed(() => {
  return content.value.trim().length > 0;
});

const imageUrls = computed(() => {
  return mediaFiles.value
    .filter((media) => media.type === "image")
    .map((media) => media.url);
});

// 方法
const goBack = () => {
  uni.navigateBack();
};

const selectCategory = (categoryId: string) => {
  selectedCategory.value = categoryId;
};

const showMediaSelector = () => {
  showMediaModal.value = true;
};

const hideMediaSelector = () => {
  showMediaModal.value = false;
};

const chooseImage = () => {
  hideMediaSelector();
  uni.chooseImage({
    count: 9 - mediaFiles.value.length,
    sizeType: ["compressed"],
    sourceType: ["album", "camera"],
    success: (res: any) => {
      // 显示上传提示
      uni.showLoading({
        title: "上传中...",
      });

      // 上传每个图片文件到服务器
      const uploadPromises = res.tempFilePaths.map((filePath: string) => {
        return new Promise((resolve, reject) => {
          uni.uploadFile({
            url: "/h5api/jjx/upload", // 使用正确的端口3005
            filePath: filePath,
            name: "files",
            success: (uploadResult: any) => {
              try {
                const data = JSON.parse(uploadResult.data);
                if (data.success) {
                  resolve({
                    type: "image",
                    url: `/h5api${data.data.files[0].url}`,
                    size: data.data.files[0].size,
                    filename: data.data.files[0].filename,
                  });
                } else {
                  reject(new Error(data.message || "上传失败"));
                }
              } catch (e) {
                reject(new Error("上传响应解析失败"));
              }
            },
            fail: (error: any) => {
              reject(new Error(error.errMsg || "上传失败"));
            },
          });
        });
      });

      // 等待所有图片上传完成
      Promise.all(uploadPromises)
        .then((uploadedFiles: any[]) => {
          const newMediaFiles: MediaFile[] = uploadedFiles.map((file) => ({
            type: file.type as "image" | "video",
            url: file.url,
            size: file.size,
            filename: file.filename,
          }));

          mediaFiles.value = [...mediaFiles.value, ...newMediaFiles];

          uni.hideLoading();
          uni.showToast({
            title: `成功上传${newMediaFiles.length}张图片`,
            icon: "success",
          });
        })
        .catch((error: any) => {
          console.error("上传图片失败:", error);
          uni.hideLoading();
          uni.showToast({
            title: error.message || "上传失败",
            icon: "none",
          });
        });
    },
    fail: (err: any) => {
      console.error("选择图片失败:", err);
      uni.showToast({
        title: "选择图片失败",
        icon: "none",
      });
    },
  });
};

const chooseVideo = () => {
  hideMediaSelector();
  uni.chooseVideo({
    sourceType: ["album", "camera"],
    maxDuration: 60,
    camera: "back",
    success: (res: any) => {
      // 显示上传提示
      uni.showLoading({
        title: "上传中...",
      });

      // 上传视频文件到服务器
      uni.uploadFile({
        url: "/h5api/jjx/upload", // 使用正确的端口3005
        filePath: res.tempFilePath,
        name: "files",
        success: (uploadResult: any) => {
          try {
            const data = JSON.parse(uploadResult.data);
            if (data.success) {
              const videoFile: MediaFile = {
                type: "video",
                url: `/h5api${data.data.files[0].url}`,
                poster: res.thumbTempFilePath || "",
                duration: res.duration,
                size: data.data.files[0].size,
                filename: data.data.files[0].filename,
              };

              mediaFiles.value = [...mediaFiles.value, videoFile];

              uni.hideLoading();
              uni.showToast({
                title: "视频上传成功",
                icon: "success",
              });
            } else {
              throw new Error(data.message || "上传失败");
            }
          } catch (e) {
            console.error("上传视频失败:", e);
            uni.hideLoading();
            uni.showToast({
              title: "上传失败",
              icon: "none",
            });
          }
        },
        fail: (error: any) => {
          console.error("上传视频失败:", error);
          uni.hideLoading();
          uni.showToast({
            title: error.errMsg || "上传失败",
            icon: "none",
          });
        },
      });
    },
    fail: (err: any) => {
      console.error("选择视频失败:", err);
      uni.showToast({
        title: "选择视频失败",
        icon: "none",
      });
    },
  });
};

const deleteMedia = (index: number) => {
  mediaFiles.value.splice(index, 1);
};

const previewImage = (index: number) => {
  const imageFiles = mediaFiles.value.filter((media) => media.type === "image");
  const clickedImage = mediaFiles.value[index];

  if (clickedImage.type === "image") {
    const imageIndex = imageFiles.findIndex(
      (img) => img.url === clickedImage.url
    );
    currentPreviewIndex.value = imageIndex;
    showImagePreview.value = true;
  }
};

const closeImagePreview = () => {
  showImagePreview.value = false;
  currentPreviewIndex.value = 0;
};

const onSwiperChange = (e: any) => {
  currentPreviewIndex.value = e.detail.current;
};

const goToTopicSelect = () => {
  uni.showToast({
    title: "选择话题功能",
    icon: "none",
  });
};

const onAnonymousChange = (e: any) => {
  isAnonymous.value = e.detail.value;
};

const onTopChange = (e: any) => {
  isTop.value = e.detail.value;
};

const publishPost = () => {
  if (!canPublish.value) return;

  uni.showLoading({
    title: "发布中...",
  });

  // 获取分类对应的tag
  const categoryName =
    categories.value.find((cat) => cat.id === selectedCategory.value)?.name ||
    "";

  // 构建发布数据
  const postData = {
    context: content.value.trim(),
    img: mediaFiles.value.map((file) => file.url),
    topic: [], // 暂时为空，后续可以添加话题选择功能
    anonymity: isAnonymous.value,
    tag: categoryName ? [categoryName] : [],
    author: {
      _id: "673da8f1e8a46e04b85f7b14", // 模拟用户ID
      name: isAnonymous.value ? "匿名用户" : "测试用户",
      avatar: "",
    },
    isTop: isTop.value,
  };

  console.log("发布数据:", postData);

  // 调用后端API发布动态
  uni.request({
    url: "/h5api/jjx/createessay", // 使用正确的端口3005
    method: "POST",
    header: {
      "Content-Type": "application/json",
    },
    data: postData,
    success: (response: any) => {
      uni.hideLoading();

      if (response.statusCode === 200 && response.data.success) {
        uni.showToast({
          title: "发布成功",
          icon: "success",
          duration: 1500,
        });

        console.log("发布成功:", response.data);

        // 清空表单
        content.value = "";
        mediaFiles.value = [];
        selectedCategory.value = "help";
        isAnonymous.value = false;
        isTop.value = false;

        // 发布成功后通知父页面并返回
        setTimeout(() => {
          // 获取事件通道并发送发布成功事件
          const eventChannel =
            uni.getOpenerEventChannel && uni.getOpenerEventChannel();
          if (eventChannel && eventChannel.emit) {
            eventChannel.emit("publishSuccess", {
              message: "发布成功",
              data: response.data,
            });
          }

          uni.navigateBack({
            success: () => {
              console.log("返回动态页面，页面会自动刷新");
            },
          });
        }, 1500);
      } else {
        uni.showToast({
          title: response.data?.message || "发布失败",
          icon: "none",
          duration: 3000,
        });
      }
    },
    fail: (error: any) => {
      console.error("发布失败:", error);
      uni.hideLoading();

      uni.showToast({
        title: error.errMsg || "发布失败，请重试",
        icon: "none",
        duration: 3000,
      });
    },
  });
};
</script>

<style lang="scss" scoped>
.publish-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 顶部导航 */
.header {
  background-color: #fff;
  padding-top: var(--status-bar-height);
}

.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.back-btn,
.menu-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s;

  &:active {
    background-color: #f0f0f0;
  }
}

.back-icon {
  font-size: 36rpx;
  color: #333;
  font-weight: bold;
}

.menu-icon {
  font-size: 32rpx;
  color: #666;
}

.page-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

/* 内容区域 */
.content-section {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.section-icon {
  font-size: 32rpx;
  margin-right: 12rpx;
}

.section-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #333;
  flex: 1;
}

.arrow-icon {
  font-size: 32rpx;
  color: #ccc;
}

.content-input {
  margin-bottom: 30rpx;
}

.textarea {
  width: 100%;
  min-height: 200rpx;
  font-size: 28rpx;
  line-height: 1.6;
  color: #333;
  background-color: transparent;
  resize: none;
  border: none;
  outline: none;
}

.add-media-btn {
  width: calc((100% - 40rpx) / 3);
  height: 200rpx;
  border: 2rpx dashed #ddd;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
  flex-shrink: 0;
  background-color: #fafafa;

  &:active {
    border-color: #ff6e26;
    background-color: rgba(255, 110, 38, 0.05);
  }
}

.add-icon {
  font-size: 48rpx;
  color: #999;
}

.media-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-top: 20rpx;
}

.media-item {
  position: relative;
  width: calc((100% - 40rpx) / 3);
  height: 200rpx;
  flex-shrink: 0;
}

.preview-image {
  width: 100%;
  height: 100%;
  border-radius: 12rpx;
}

.video-preview {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 12rpx;
  overflow: hidden;
}

.preview-video {
  width: 100%;
  height: 100%;
  border-radius: 12rpx;
}

.video-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 12rpx;
}

.play-icon {
  font-size: 32rpx;
  color: #fff;
}

.delete-btn {
  position: absolute;
  top: -8rpx;
  right: -8rpx;
  width: 32rpx;
  height: 32rpx;
  background-color: #ff4757;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.delete-icon {
  font-size: 20rpx;
  color: #fff;
  line-height: 1;
}

/* 圈子类型 */
.category-section {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
}

.category-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
}

.category-tag {
  padding: 12rpx 24rpx;
  background-color: #f8f8f8;
  border-radius: 40rpx;
  font-size: 26rpx;
  color: #666;
  transition: all 0.2s;

  &.active {
    background-color: #ff6e26;
    color: #fff;
  }

  &:active {
    transform: scale(0.95);
  }
}

/* 选择话题 */
.topic-section {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
  transition: background-color 0.2s;

  &:active {
    background-color: #f8f8f8;
  }
}

/* 发布设置 */
.settings-section {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;

  &:not(:last-child) {
    border-bottom: 1rpx solid #f0f0f0;
  }
}

.setting-label {
  font-size: 28rpx;
  color: #333;
}

.setting-switch {
  transform: scale(0.8);
}

/* 发布按钮 */
.publish-btn-container {
  padding: 30rpx;
}

.publish-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #ff6e26, #ff8a50);
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: 600;
  color: #fff;
  border: none;
  transition: all 0.2s;

  &:active {
    transform: scale(0.98);
  }

  &.disabled {
    background: #ccc;
    color: #999;
    transform: none;
  }
}

/* 媒体选择弹窗 */
.media-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: #fff;
  border-radius: 16rpx;
  margin: 40rpx;
  min-width: 500rpx;
  max-width: 600rpx;
  overflow: hidden;
}

.modal-header {
  padding: 40rpx 30rpx 20rpx;
  text-align: center;
  border-bottom: 1rpx solid #f0f0f0;
}

.modal-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.modal-body {
  padding: 30rpx;
  text-align: center;
}

.modal-text {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
}

.modal-actions {
  display: flex;
  padding: 20rpx;
  gap: 20rpx;
}

.action-btn {
  flex: 1;
  height: 80rpx;
  border: none;
  border-radius: 12rpx;
  font-size: 28rpx;
  font-weight: 500;
  transition: all 0.2s;

  &:active {
    transform: scale(0.95);
  }
}

.image-btn {
  background-color: #f8f8f8;
  color: #333;

  &:active {
    background-color: #e8e8e8;
  }
}

.video-btn {
  background-color: #f8f8f8;
  color: #333;

  &:active {
    background-color: #e8e8e8;
  }
}

/* 图片预览弹窗 */
.image-preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.9);
  z-index: 2000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-swiper {
  width: 100%;
  height: 100%;
}

.swiper-item-container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40rpx;
}

.preview-full-image {
  max-width: 100%;
  max-height: 100%;
  border-radius: 8rpx;
}

.close-preview-btn {
  position: absolute;
  top: 60rpx;
  right: 40rpx;
  width: 80rpx;
  height: 80rpx;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
  transition: all 0.2s;

  &:active {
    transform: scale(0.9);
    background-color: rgba(0, 0, 0, 0.7);
  }
}

.close-icon {
  font-size: 48rpx;
  color: #fff;
  line-height: 1;
  font-weight: bold;
}

.image-counter {
  position: absolute;
  bottom: 80rpx;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.6);
  padding: 12rpx 24rpx;
  border-radius: 40rpx;
  z-index: 100;
}

.counter-text {
  font-size: 28rpx;
  color: #fff;
  line-height: 1;
}

/* 响应式适配 */
@media screen and (max-width: 750rpx) {
  .nav-bar {
    height: 80rpx;
    padding: 0 20rpx;
  }

  .page-title {
    font-size: 30rpx;
  }

  .content-section,
  .category-section,
  .topic-section,
  .settings-section {
    margin: 15rpx;
    padding: 24rpx;
  }

  .textarea {
    min-height: 160rpx;
    font-size: 26rpx;
  }

  .media-preview {
    gap: 15rpx;
  }

  .media-item {
    width: calc((100% - 30rpx) / 3);
    height: 180rpx;
  }

  .add-media-btn {
    width: calc((100% - 30rpx) / 3);
    height: 180rpx;
  }

  .add-icon {
    font-size: 40rpx;
  }

  .category-tag {
    padding: 10rpx 20rpx;
    font-size: 24rpx;
  }

  .publish-btn {
    height: 80rpx;
    font-size: 30rpx;
  }

  .modal-content {
    margin: 30rpx 20rpx;
    min-width: auto;
  }

  .modal-header {
    padding: 30rpx 20rpx 15rpx;
  }

  .modal-title {
    font-size: 30rpx;
  }

  .modal-body {
    padding: 20rpx;
  }

  .modal-text {
    font-size: 26rpx;
  }

  .action-btn {
    height: 70rpx;
    font-size: 26rpx;
  }

  .close-preview-btn {
    top: 40rpx;
    right: 30rpx;
    width: 70rpx;
    height: 70rpx;
  }

  .close-icon {
    font-size: 40rpx;
  }

  .image-counter {
    bottom: 60rpx;
    padding: 10rpx 20rpx;
  }

  .counter-text {
    font-size: 26rpx;
  }

  .swiper-item-container {
    padding: 30rpx;
  }
}
</style>
